package com.tianyang.yukuaifuzs.common.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.base.YkfApplication;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.jump.eventbus.RefreshDownloadEvent;
import com.tianyang.yukuaifuzs.rxservice.client.DownloadClient;
import com.tianyang.yukuaifuzs.utils.NetworkUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * Description：APP更新下载service
 * Created by 薛勇军 on 2021/1/21.
 */
public class DownloadIntentService extends IntentService {

    private static final String TAG = "DownloadIntentService";

    private NotificationManager mNotifyManager;

    private Notification mNotification;

    private String mDownloadFileName;

    private int id = 11123;

    public DownloadIntentService() {
        super("InitializeService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null || intent.getExtras() == null) return;
        String downloadUrl = intent.getExtras().getString("download_url");
        final String downloadId = intent.getExtras().getString("download_id");
        mDownloadFileName = intent.getExtras().getString("download_file");

        if (TextUtils.isEmpty(downloadUrl)) {
            this.stopSelf();
            return;
        }

        Log.d(TAG, "download_url --" + downloadUrl);
        Log.d(TAG, "download_file --" + mDownloadFileName);

        String baseUrl = NetworkUtils.getDomain(downloadUrl);
        if (!TextUtils.isEmpty(baseUrl)) {
            String downloadAbsUrl = downloadUrl.substring(baseUrl.length());
            final File file = new File(CommonConfig.APP_ROOT_PATH + CommonConfig.DOWNLOAD_DIR + mDownloadFileName);
            long range = 0;
            int progress = 0;
            if (file.exists()) {
                range = SPDownloadUtil.getInstance().get(downloadAbsUrl, 0);
                progress = (int) (range * 100 / file.length());
                if (range == file.length()) {
                    installApp(file);
                    EventBus.getDefault().post(new RefreshDownloadEvent(100));
                    return;
                }
            }

            final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_notify_download);
            remoteViews.setProgressBar(R.id.pb_progress, 100, progress, false);
            remoteViews.setTextViewText(R.id.tv_progress, "已下载" + progress + "%");

            mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(downloadId, mDownloadFileName, NotificationManager.IMPORTANCE_LOW);
                Toast.makeText(this, mChannel.toString(), Toast.LENGTH_SHORT).show();
                Log.i(TAG, mChannel.toString());
                mNotifyManager.createNotificationChannel(mChannel);
                mNotification = new Notification.Builder(this)
                        .setChannelId(downloadId)
                        .setCustomContentView(remoteViews)
                        .setTicker("正在下载")
                        .setSmallIcon(R.mipmap.ic_launcher).build();
            } else {
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setCustomContentView(remoteViews)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setTicker("正在下载")
                        .setOngoing(true)
                        .setChannelId(downloadId);//无效
                mNotification = notificationBuilder.build();
            }
            mNotifyManager.notify(id, mNotification);

            Log.d(TAG, "range = " + range);
            DownloadClient.getInstance(baseUrl).downloadFile(range, downloadAbsUrl, mDownloadFileName, new DownloadCallBack() {
                @Override
                public void onProgress(int progress) {
                    Log.d(TAG, "已下载" + progress + "%");
                    remoteViews.setProgressBar(R.id.pb_progress, 100, progress, false);
                    remoteViews.setTextViewText(R.id.tv_progress, "已下载" + progress + "%");
                    mNotifyManager.notify(id, mNotification);
                    EventBus.getDefault().post(new RefreshDownloadEvent(progress));
                }

                @Override
                public void onCompleted() {
                    Log.d(TAG, "下载完成");
                    mNotifyManager.cancel(id);
                    installApp(file);
                    EventBus.getDefault().post(new RefreshDownloadEvent(100));
                }

                @Override
                public void onError(String msg) {
                    Log.d(TAG, "下载发生错误--" + msg);
                    mNotifyManager.cancel(id);
                    EventBus.getDefault().post(new RefreshDownloadEvent(-1));
                }
            });
        }
    }

    private void installApp(File file) {
        //判断是否是AndroidN以及更高的版本
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(YkfApplication.getInstance(),
                    YkfApplication.getInstance().getPackageName() + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }
}
